<script setup>
import PageHeader from "@/components/PageHeader/index.vue";
import {nextTick, onMounted, ref} from "vue";
import {delCompetitionApply, listStudentCompetition, postCompetitionApply } from "@/api/competition/index.js";
import {
  convertISOToBasicString, cptDateFormat,
  cptStatusDict,
  cptStatusFormat, getPartModeDict, getPartTypeDict
} from "@/utils/common1.js";
import Pagination from "@/components/Pagination/index.vue";
import StepHeader from "@/components/StepHeader/index.vue";
import {ElMessage} from "element-plus";
import {postPaperDel} from "@/api/paper.js";
import SubmittedStatus from "@/components/MissionStatus/SubmittedStatus.vue";
import ApprovedStatus from "@/components/MissionStatus/ApprovedStatus.vue";
import RejectedStatus from "@/components/MissionStatus/RejectedStatus.vue";
import NotAwardedStatus from "@/components/MissionStatus/NotAwardedStatus.vue";
import PendingApprovalStatus from "@/components/MissionStatus/PendingApprovalStatus.vue";
import SuccessfulRecognitionStatus from "@/components/MissionStatus/SuccessfulRecognitionStatus.vue";
import FailedRecognitionStatus from "@/components/MissionStatus/FailedRecognitionStatus.vue";
import Steps from "@/components/Steps/index.vue";
//查询条件
const queryParams = ref({
  current: 1,
  size: 20,
  data: {
    status: null,
    startTime: null,
    endTime: null,
    uid: null,
    name: null,
    competitionName: null,
  }
})

//查询条件控制
const queryParamsControl = ref({
  table: {
    total: 0,
    loading: false,
    data: []
  },
  status: {
    option: [],
    loading: false
  }
})

const statusDict = ref([])

//竞赛方式dict 线上/线下
const partModeDict = ref([])

//参与方式dict 个人/团队
const partTypeDict = ref([])

//表格ref
const tableRef = ref(null)


// 拿取表格信息
async function getList() {
  queryParamsControl.value.table.loading = true
  const data = await listStudentCompetition(queryParams.value)
  console.log("data:",data)

  queryParamsControl.value.table.data = data.data
  queryParamsControl.value.table.total = data.count
  queryParamsControl.value.table.loading = false
}

// 刷新
function handleQuery() {
  queryParams.value.current = 1
  getList()
}

// 删除申请
const delApply = async (row) => {
  const res = await delCompetitionApply(row.id);
  if(!res.code) {
    ElMessage.success('已删除该申请')
  } else {
    console.log("delApply:",res)
    ElMessage.error("删除失败，请重试")
  }
  await getList();
};

// 提交申请弹窗
let formRef=ref(null)
let dialogVisible_apply = ref(false)
let dialogVisible_check = ref(false)

const dialogController_apply = () => {
  dialogVisible_apply.value = true;
};

let date_apply = ref('')
const handleDate_apply = (value) => {
  applyForm.value.competitionTime = convertISOToBasicString(value)
}

const handleClose_apply = () => {
  dialogVisible_apply.value = false;
  nextTick(() => {
    formRef.value.clearValidate()
  });
};

const handleReset_apply = () => {
  applyForm.value = {
    competitionName: '',
    competitionTutor: '',
    competitionPosition: '',
    competitionTime: '',
    participantType: '',
    participationMode: '',
    teamMembers: '',
    teamRank: '',
  }
  date_apply.value = ''
}

let applyForm = ref({
  competitionName: '',
  competitionTutor: '',
  competitionPosition: '',
  competitionTime: '',
  participantType: '',
  participationMode: '',
  teamMembers: '',
  teamRank: '',
})

const applyForm_rules = ref({
  competitionName: [
    {
      required: true,
      message: "请输入竞赛名称",
      trigger: "blur",
    },
  ],
  competitionTutor: [
    {
      required: true,
      message: "请输入导师",
      trigger: "blur",
    },
  ],
  competitionPosition: [
    {
      required: true,
      message: "请输入竞赛地点",
      trigger: "blur",
    },
  ],
  date_apply: [
    {
      required: true,
      message: "请选择竞赛时间",
      trigger: "blur",
    },
  ],
  participationMode: [
    {
      required: true,
      message: "请选择竞赛方式",
      trigger: "blur",
    },
  ],
  participantType: [
    {
      required: true,
      message: "请选择参与方式",
      trigger: "blur",
    },
  ],
  teamMembers: [
    {
      required: true,
      message: "请输入队友姓名",
      trigger: "blur",
    },
  ],
  teamRank: [
    {
      required: true,
      message: "请输入团队顺位",
      trigger: "blur",
    },
  ],

})
//开始写操作栏中的进度展示
const statusComponents = {
  0: SubmittedStatus,
  1: ApprovedStatus,
  2: RejectedStatus,
  3: NotAwardedStatus,
  4: PendingApprovalStatus,
  5: SuccessfulRecognitionStatus,
  6: FailedRecognitionStatus,
};
//进度条显示
const statusSteps = {
  0: 1,
  1: 2,
  2: 2,
  3: 2,
  4: 3,
  5: 4,
  6: 2,
};
// 视图状态
let currentStatus = ref(null) //进度条
let currentStatusComponent = ref(null);
let dialogVisible_progress = ref(false);  // 控制 dialog 显示
let currentRowData = ref(null);  // 保存当前行数据，用来传递给子组件

const viewProgress = (row) => {

  console.log("viewProgress 被调用", row);  // 调试：查看是否调用了这个函数
  const status = row.status;
  console.log("当前状态:", status);  // 调试：查看当前的状态值

  // 根据状态选择对应的子组件
  currentStatusComponent.value = statusComponents[status] || null;
  currentStatus.value = statusSteps[status] || null;

  // 设置当前行的数据，用于传递给子组件
  currentRowData.value = row;

  console.log("当前状态组件:", currentStatusComponent.value);  // 调试：确认组件是否赋值成功

  // 打开 dialog
  dialogVisible_progress.value = true;
};

    // 关闭对话框的方法
    const closeDialogProgress = () => {
      dialogVisible_progress.value = false; // 关闭对话框
      currentRowData.value = null; // 可选：清空当前行数据
      currentStatusComponent.value = null; // 可选：重置当前状态组件
      currentStatus.value = null;
      console.log('Dialog 已关闭');
    };

// 关闭处理
const handleClose_dialog = () => {
  dialogVisible_progress.value = false;  // 关闭 dialog
  currentStatusComponent.value = null;  // 清除当前组件
  currentStatus.value = null;
  currentRowData.value = null;  // 清除当前行数据
};


const postCptApply = async () => {
  const data = await postCompetitionApply(applyForm.value)
  if(!data.code) {
    dialogVisible_check.value = false
    dialogVisible_apply.value = false
    ElMessage.success('提交成功')
    handleReset_apply()
    await getList()
  } else {
    console.log("postCptApply",data)
    ElMessage.error('请重新提交')
  }
}

onMounted(() => {
  getList()
  statusDict.value = cptStatusDict()
  partModeDict.value = getPartModeDict()
  partTypeDict.value = getPartTypeDict()
})

</script>

<template>
  <div class="app-container">
    <el-card class="box">
      <PageHeader>
        <template #left>
          <ElButton class="exportBtn" type="success" @click="dialogController_apply">
            <el-icon><Plus /></el-icon>新增申报
          </ElButton>
        </template>
        <template #right>
          <ElButton class="queryBtn" plain @click="handleQuery">刷新列表</ElButton>
        </template>
      </PageHeader>
    </el-card>
    <el-card class="box">
      <el-table
          height="400"
          ref="tableRef"
          v-loading="queryParamsControl.table.loading"
          :data="queryParamsControl.table.data"
          row-key="id"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="table_description">
              <el-descriptions :column="3" class="cell_description" border>
                <el-descriptions-item label="导师">{{props.row.competitionTutor}}</el-descriptions-item>
                <el-descriptions-item label="参与方式">{{partTypeDict[props.row.participantType].label}}</el-descriptions-item>
                <el-descriptions-item label="团队顺位" v-if="props.row.participantType"
                >{{props.row.teamRank}}</el-descriptions-item>
                <el-descriptions-item label="队友" v-if="props.row.participantType"
                >{{props.row.teamMembers}}</el-descriptions-item>
                <el-descriptions-item label="竞赛方式">{{partModeDict[props.row.participationMode].label}}</el-descriptions-item>
                <el-descriptions-item label="举办地点" v-if="props.row.participationMode"
                >{{props.row.competitionPosition}}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" fixed="left" reserve-selection width="50" />
        <el-table-column type="index" fixed="left" width="54" label="序号" />
        <el-table-column label="竞赛名称" prop="competitionName" show-overflow-tooltip />
        <ElTableColumn label="竞赛时间" prop="competitionTime" :formatter="cptDateFormat()" width="120" show-overflow-tooltip />
        <ElTableColumn label="申请状态" prop="status" :formatter="cptStatusFormat()" show-overflow-tooltip />
        <ElTableColumn label="申请创建时间" prop="createTime" show-overflow-tooltip />
        <ElTableColumn label="操作" width="124" fixed="right">
          <template #default="{row}">
            <el-button
                plain
                type="primary"
                @click="viewProgress(row)"
                link>查看申报进度</el-button>
          </template>
        </ElTableColumn>
      </el-table>
    </el-card>

<!--    新建申报-->
    <el-dialog
        v-model="dialogVisible_apply"
        width="650"
        :before-close="handleClose_apply">
      <div style="height: 52vh">
        <el-scrollbar max-height="360" wrap-style="overflow-x: hidden">
          <div style="width: 100%">
            <el-form ref="formRef" :model="applyForm" :rules="applyForm_rules" inline>
              <StepHeader title="参赛信息" />
              <el-row>
                <el-col :span="24">
                  <el-form-item label="竞赛名称" prop="competitionName">
                    <el-input style="width: 350px" v-model="applyForm.competitionName"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="导师" prop="competitionTutor">
                    <el-input style="width: 365px" v-model="applyForm.competitionTutor"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="竞赛时间" prop="date_apply">
                    <el-date-picker
                        v-model="date_apply"
                        type="datetime"
                        placeholder="请选择"
                        format="YYYY/MM/DD HH:mm:ss"
                        @change="handleDate_apply"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="竞赛方式" prop="participationMode">
                    <el-select
                        v-model="applyForm.participationMode"
                        style="width: 120px"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="item in partModeDict"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" v-if="applyForm.participationMode">
                  <el-form-item label="举办地点" prop="competitionPosition">
                    <el-input v-model="applyForm.competitionPosition"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="10">
                  <el-form-item label="参与方式" prop="participantType">
                    <el-select
                        v-model="applyForm.participantType"
                        style="width: 120px"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="item in partTypeDict"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10" v-if="applyForm.participantType">
                  <el-form-item label="团队顺位" prop="teamRank">
                    <el-input v-model="applyForm.teamRank"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="applyForm.participantType">
                <el-col :span="24">
                  <el-form-item label="队友" prop="teamMembers">
                    <el-input style="width: 365px" v-model="applyForm.teamMembers"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-scrollbar>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleReset_apply">重置</el-button>
          <el-button type="success" @click="dialogVisible_check=true">
            提交
          </el-button>
        </div>
      </template>
      <el-dialog
          v-model="dialogVisible_check"
          width="400"
          append-to-body
      >
        <span>确定提交吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible_check=false">取消</el-button>
            <el-button type="success" @click="postCptApply">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-dialog>

    <el-dialog v-model="dialogVisible_progress" width="650" :before-close="handleClose_dialog" >
      <Steps v-model="currentStatus"></Steps>
                <!-- 动态加载状态组件，并传递当前行数据 -->
                <component :is="currentStatusComponent" 
                :application="currentRowData" 
                @closeDialog="closeDialogProgress"
                @hanleQeury="handleQuery"/>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.box {
  margin-bottom: 8px;
}

.table_description {
  padding-left: 150px;
}


</style>